package qjc.z_排序;

import java.util.Arrays;

public class z3_堆排序 {
    /**
     * 建立大顶堆，交换，下潜
     *
     * @param nums
     */
    private static void sort(int[] nums) {
        heapify(nums, nums.length);
        for (int i = nums.length - 1; i > 0; i--) {
            swap(nums, 0, i);
            down(nums, 0, i);
        }
    }

    private static void heapify(int[] nums, int length) {
        for (int i = length / 2 - 1; i >= 0; i--) {
            down(nums, i, length);
        }
    }

    private static void down(int[] nums, int parent, int size) {
        while (true) {
            int left = parent * 2 + 1;
            int right = left + 1;
            int max = parent;
            if (left < size && nums[left] > nums[max]) {
                max = left;
            }
            if (right < size && nums[right] > nums[max]) {
                max = right;
            }
            if (max == parent) {
                break;
            }
            swap(nums, parent, max);
            parent = max;
        }

    }

    private static void swap(int[] nums, int parent, int max) {
        int temp = nums[max];
        nums[max] = nums[parent];
        nums[parent] = temp;
    }

    public static void main(String[] args) {
        int[] a = {2, 3, 1, 7, 6, 4, 5};
        System.out.println(Arrays.toString(a));
        sort(a);
        System.out.println(Arrays.toString(a));
    }
}
